﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommandLib;

namespace BackEnd.Controllers
{
    public class CommonController : Controller
    {
        [HttpPost]
        [AllowAnonymous]
        [ValidateInput(false)]
        public JsonResult UploadAndReadFile()
        {
            string content = string.Empty;
            try
            {
                var files = Request.Files;
                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
                        content = new StreamReader(file.InputStream).ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return Json(new { content }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateInput(false)]
        public JsonResult UploadImage()
        {
            string imageName;
            string fileName = string.Empty;
            try
            {
                var files = Request.Files;
                if (files.Count > 0)
                {
                    if (!Directory.Exists(Config.FolderImage))
                    {
                        Directory.CreateDirectory(Config.FolderImage);
                    }
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
                        imageName = file.FileName;
                        var lastIndexOfDot = imageName.LastIndexOf(".");
                        if (lastIndexOfDot > -1)
                        {
                            fileName = string.Format("{0}_{1}{2}", file.FileName.Substring(0, lastIndexOfDot - 1),
                                DateTime.Now.Ticks.ToString(),
                                file.FileName.Substring(lastIndexOfDot));
                            string filePath = Path.Combine(
                                Config.FolderImage,
                                fileName);
                            file.SaveAs(filePath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return Json(new { fileName }, JsonRequestBehavior.AllowGet);
        }
    }
}
